import chardet
from pathlib import Path

def detect_encoding(file_path):
    """检测文件编码。"""
    with open(file_path, 'rb') as f:
        result = chardet.detect(f.read())
        return result['encoding']

def list_files_with_encodings(directory):
    """遍历指定目录下的所有文件"""
    directory_path = Path(directory)
    for file in directory_path.glob("**/*.txt"):  # 遍历指定目录下的所有文件
        result = chardet.detect_all(open(file, 'rb').read())
        encodings = sorted(result, key=lambda x: x['confidence'], reverse=True)[:3]  # 按置信度排序并取前3个
        print(f"文件名: {file.name}")
        for i, encoding in enumerate(encodings, start=1):
            print(f"  {i}. 编码: {encoding['encoding']}, 置信度: {encoding['confidence']}")

directory_to_search = r"D:\00\编码判断"
list_files_with_encodings(directory_to_search)